<template>
  <!--列表-->
  <router-exact-view name="student">
    <div style="width: 100%" class="template-list-page-container">
      <div class="search-area">
        <search-form-container>
          <el-form :inline="true" :model="searchForm">
            <el-form-item label="学生姓名">
              <el-input v-model="searchForm.studentName" placeholder="请输入学生姓名" />
            </el-form-item>
            <el-form-item label="是否同意送教">
              <el-select
                v-model="searchForm.isConsentOutwork"
                placeholder="请选择是否同意送教"
              >
                <el-option label="全部" :value="-1" />
                <el-option label="是" :value="1" />
                <el-option label="否" :value="2" />
              </el-select>
            </el-form-item>
            <el-form-item label="是否毕业">
              <el-select
                v-model="searchForm.status"
                placeholder="请选择是否毕业"
              >
                <el-option label="全部" :value="-1" />
                <el-option label="是" :value="2" />
                <el-option label="否" :value="1" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handlePageChange(1)">查  询</el-button>
              <el-button @click="resetSearchForm">重  置</el-button>
            </el-form-item>
          </el-form>
        </search-form-container>
      </div>
      <my-table
        v-loading="loading"
        :columns="columns"
        :data-source="data"
        :pagination="pagination"
        :btn-options="btnOptions"
        title="学生列表"
        @page-change="handlePageChange"
      >
        <div slot="table-btn">
          <el-button type="primary" @click="addStudent">新增学生</el-button>
          <el-button type="primary" @click="openImportDialog">导入学生信息</el-button>
          <el-button type="primary" @click="exportStudentByCondition">导出查询结果</el-button>
          <el-button type="primary" @click="exportStudentSend">导出送教学生表</el-button>
          <el-button type="primary" @click="exportStudentDontSend">导出适龄未送教表</el-button>
        </div>
      </my-table>
      <el-dialog
        title="导入学生信息"
        :visible.sync="dialogVisible"
      >
        <a href="https://img.speschool.com/speschool/student-template.xlsx" style="color: #409EFF; display: inline-block; margin-bottom: 10px;">点击下载学籍表导入模板</a>
        <my-upload
          :action="importInterfaceUrl"
          :limit="1"
          list-type="text"
          img-type="xls,xlsx"
          @transferResponse="handleImport"
        />
        <div class="tips">
          <p>注：为保证导入数据正确性，请按下方规范输入，如果不符合要求，将导入失败。</p>
          <p>1. 请先点击上面链接下载导入模板，在模板中按规范填写信息后，再按【点击上传】按钮导入学生信息。</p>
          <p>2. 导入完成后，会显示本次导入的完成情况。由于输入格式问题，可能出现部分数据导入出错，届时请按提示挑出错误的数据修改后再重新上传。</p>
          <p>3. 残疾类型取值 【言语】【智力】【听力】【视力】【多重残疾】【肢体】。</p>
          <p>4. 户口性质取值 【农业户口】【非农业户口】。</p>
          <p>5. 政治面貌取值 【党员】【团员】【群众】。</p>
          <p>6. 年级填写1~9的数字，班级填写1~9的数字。</p>
          <p>7. 所属乡镇取值 【城关镇】 【威戎镇】 【界石铺镇】 【八里镇】 【李店镇】 【古城镇】 【仁大镇】 【甘沟镇】 【城川镇】 【曹务镇】 【雷大镇】 【四河镇】 【细巷镇】 【双岘镇】 【治平镇】 【红寺镇】 【原安镇】 【司桥乡】 【余湾乡】 【贾河乡】 【深沟乡】 【新店乡】 【三合乡】 【灵芝乡】。</p>
          <p>8. 出生日期输入标准 2021-11-22。</p>
          <p>9. 入学年月输入标准 2021-06。</p>
        </div>
        <div v-if="showImportResult" style="margin: 10px 0;">导入结果：共导入 <span style="color: #e6a23c;">{{ importResult.totalNum }}条</span> 学生信息，成功 <span style="color: #67c23a;">{{ importResult.successNum }}条</span>，失败 <span style="color: #f56c6c;">{{ importResult.errorNum }}条</span>，失败原因如下：</div>
        <el-table
          v-if="showImportResult && showTable"
          :data="importResult.errorRows"
          stripe
          style="width: 100%"
          max-height="300"
        >
          <el-table-column
            prop="row"
            label="错误行号"
            width="100"
          />
          <el-table-column
            prop="error"
            label="错误原因"
          />
        </el-table>
        <div v-if="showImportResult && showTable" class="tips">
          <p>注：错误行号指的是excel中数据对应的行号，从2开始，第一行为标题。</p>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="closeImportDialog">关闭</el-button>
        </span>
      </el-dialog>
    </div>
  </router-exact-view>
</template>

<script>
import {
  getStudentList,
  getAllTerm
} from '@/api/basic'
import MyTable from '@/components/my-table/index'
import SearchFormContainer from '@/components/search-form-container/index'
import RouterExactView from '@/components/routerExactView'
import MyUpload from '@/components/my-upload/index'
import { studentColumns } from '../columns'

const isProd = process.env.NODE_ENV === 'production'

export default {
  components: { RouterExactView, MyTable, SearchFormContainer, MyUpload },
  data() {
    const that = this
    return {
      dialogVisible: false,
      showImportResult: false,
      showTable: false,
      importResult: {
        errorRows: [],
        errorNum: 0,
        successNum: 0,
        totalNum: 0
      },
      // 导出送教学生表
      exportSendInterfaceUrl: isProd ? 'https://jn.speschool.com/api/outwork/exportOutwork' : 'http://192.168.0.88:19999/api/outwork/exportOutwork',
      // 导出未送教学生表
      exportNoSendInterfaceUrl: isProd ? 'https://jn.speschool.com/api/student/exportNoOutworkStudent' : 'http://192.168.0.88:19999/api/student/exportNoOutworkStudent',
      // 按查询条件导出学生表接口
      exportInterfaceUrl: isProd ? 'https://jn.speschool.com/api/student/exportStudent' : 'http://192.168.0.88:19999/api/student/exportStudent',
      // 导入学生表接口
      importInterfaceUrl: isProd ? 'https://jn.speschool.com/api/student/import' : 'http://192.168.0.88:19999/api/student/import',
      currentTerm: {},
      /* 列表相关 */
      columns: studentColumns,
      data: [],
      searchForm: {
        studentName: '',
        isConsentOutwork: -1,
        status: 1
      },
      loading: false,
      pagination: {
        current: 1,
        pageSize: 10,
        total: 0
      },
      btnOptions: [
        {
          name: '查看详情',
          handler: function(row) {
            that.$router.push({ path: `/basic/student/detail/${row.id}` })
          }
        },
        {
          name: '编辑学生',
          handler: function(row) {
            that.$router.push({ path: `/basic/student/edit/${row.id}` })
          }
        },
        {
          name: '送教设置',
          handler: function(row) {
            that.$router.push({ path: `/basic/student/set/${row.id}` })
          }
        }
      ]
    }
  },
  mounted() {
    if (this.$route.name === 'student') {
      this.getTermList()
      this.handlePageChange()
    }
  },
  methods: {
    async getTermList() {
      try {
        const res = await getAllTerm({
          status: 1
        })
        if (res && res.length) {
          this.currentTerm = res[0]
        }
      } catch (err) {
        console.log(err)
      }
    },
    exportStudentSend() {
      const that = this
      if (this.currentTerm && this.currentTerm.id) {
        this.$confirm(`该操作将导出当前学期（${this.currentTerm.name}）中，所有创建了送教任务的学生名单！`, '提示', {
          confirmButtonText: '确认导出',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
          window.open(`${that.exportSendInterfaceUrl}?schoolTermId=${that.currentTerm.id}&token=${that.$store.getters.token}`)
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消导出操作'
          })
        })
      } else {
        this.$message.error('请先创建学期再进行该操作！')
      }
    },
    exportStudentDontSend() {
      const that = this
      if (this.currentTerm && this.currentTerm.id) {
        this.$confirm(`该操作将导出当前学期（${this.currentTerm.name}）中，所有未毕业且未创建送教任务的学生名单！`, '提示', {
          confirmButtonText: '确认导出',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
          window.open(`${that.exportNoSendInterfaceUrl}?schoolTermId=${that.currentTerm.id}&token=${that.$store.getters.token}`)
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消导出操作'
          })
        })
      } else {
        this.$message.error('请先创建学期再进行该操作！')
      }
    },
    exportStudentByCondition() {
      const params = JSON.parse(JSON.stringify(this.searchForm))
      if (params.isConsentOutwork === -1) {
        delete params.isConsentOutwork
      }
      if (params.status === -1) {
        delete params.status
      }
      delete params.studentName
      let str = ''
      for (const key in params) {
        str += `${key}=${params[key]}&`
      }
      window.open(`${this.exportInterfaceUrl}?${str}token=${this.$store.getters.token}`)
    },
    openImportDialog() {
      this.dialogVisible = true
      this.importResult = {
        errorRows: [],
        errorNum: 0,
        successNum: 0,
        totalNum: 0
      }
      this.showImportResult = false
      this.showTable = false
    },
    closeImportDialog() {
      this.dialogVisible = false
    },
    handleImport(res) {
      if (res.code === 100) {
        this.importResult = res.result
        this.showImportResult = true
        if (res.result.errorNum > 0) {
          this.showTable = true
        }
      }
    },
    async handlePageChange(current, size) {
      if (current) {
        this.pagination.current = current
      }
      if (size) {
        this.pagination.pageSize = size
      }
      this.loading = true
      try {
        const params = JSON.parse(JSON.stringify(this.searchForm || {}))
        if (!params.studentName) {
          delete params.studentName
        }
        if (!params.isConsentOutwork || params.isConsentOutwork === -1) {
          delete params.isConsentOutwork
        }
        if (!params.status || params.status === -1) {
          delete params.status
        }
        const res = await getStudentList({
          ...params,
          pageNum: this.pagination.current,
          pageSize: this.pagination.pageSize
        })
        if (res && res.list) {
          this.data = res.list
          this.pagination = {
            current: res.pageNum,
            pageSize: res.pageSize,
            total: res.totalElements
          }
        }
        this.loading = false
      } catch (err) {
        this.loading = false
        console.log('接口出错')
      }
    },
    resetSearchForm() {
      this.searchForm = {
        studentName: '',
        isConsentOutwork: -1,
        status: 1
      }
      this.handlePageChange(1)
    },
    addStudent() {
      this.$router.push({
        path: '/basic/student/add'
      })
    }
  }
}
</script>
<style scoped lang="less">
  @import "../../common.css";
  /* 查询条件容器的样式 */
  .search-area {
    padding: 16px 16px 0;
    margin-bottom: 8px;
    background: #fff;
  }
  .tips {
    color: red;
    font-size: 12px;
    margin-top: 20px;
    p {
      padding: 0;
      margin: 0;
      line-height: 20px;
    }
  }
</style>
